use synet::common::{MiddlewareRejectType, MiddlewareStruct, RequestStruct};
use synet::defaults::tcp;
use synet::{log, route::Route, server};

#[tokio::main]
async fn main() {
    let status = server::Server::new()
        .set_protocol(tcp::Proto::new("127.0.0.1:8899"))
        .set_open_log(true)
        .set_debug(true)
        .set_log_file("logs/log_file.txt")
        .set_log_file_max_num(30)
        .set_log_level(log::LEVEL::Trace)
        .add_route(Route::new("1001", demo_handle))
        // The execution order of middleware is consistent with the order in which it joins the service
        .add_middleware(demo_middleware)
        .start();
    
    if let Err(e) = status.await {
        println!("Error: {:?}", e)
    }
}

pub fn demo_handle(params: RequestStruct) {
    let msg = params.read;
    log::info(format!("Received message: {:?}", msg));
    let _ = params.send.try_send(msg.to_vec());
}

pub fn demo_middleware(params: RequestStruct) -> MiddlewareStruct {
    println!("Middleware: {:?}", params);
    // MiddlewareRejectType::Reject -> 拒绝服务
    // MiddlewareRejectType::RejectAndClose -> 拒绝并关闭连接
    let mut res = MiddlewareStruct::new(params);
    // res.reject_type = MiddlewareRejectType::Reject;
    res
}

#[tokio::test]
async fn tcp_request_test() {
    use std::io::ErrorKind;
    use synet::defaults::tcp::MessageStruct;
    use tokio::io::AsyncWriteExt;
    use tokio::net::TcpStream;
    // 连接的服务器地址和端口
    let addr = "127.0.0.1:8899";

    // 连接到服务器
    let stream = match TcpStream::connect(addr).await {
        Ok(stream) => stream,
        Err(e) => {
            panic!("连接服务器失败: {:?}", e);
        }
    };

    // 要发送的数据
    let message = MessageStruct {
        route_key: format!("1001"),
        message: format!("Hello, Server!"),
    };
    let data_to_send = serde_json::to_string(&message).unwrap();

    // 添加4字节长度的包头用于描述数据长度
    let data_length = data_to_send.len() as u32;
    let mut data_to_send_with_header = vec![0; 4];
    data_to_send_with_header.extend_from_slice(&data_to_send.into_bytes());
    data_to_send_with_header[0..4].copy_from_slice(&data_length.to_be_bytes());

    let (read, mut write) = stream.into_split();
    tokio::spawn(async move {
        loop {
            let mut buffer = vec![0; 1024];
            match read.try_read(&mut buffer) {
                Ok(len) => {
                    let response = String::from_utf8_lossy(&buffer[0..len]);
                    println!("收到服务器响应: {:?}", response);
                }
                Err(e) if e.kind() == ErrorKind::WouldBlock => {
                    let _ = read.readable().await;
                    continue;
                }
                Err(e) => {
                    panic!("接收响应失败: {:?}", e);
                }
            }
        }
    });

    // 模拟发送粘包数据
    match write.write_all(data_to_send_with_header.as_slice()).await {
        Ok(_) => println!("数据已成功发送"),
        Err(e) => {
            panic!("发送数据失败: {:?}", e);
        }
    }
    match write.write_all(data_to_send_with_header.as_slice()).await {
        Ok(_) => println!("数据已成功发送"),
        Err(e) => {
            panic!("发送数据失败: {:?}", e);
        }
    }
    tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;
    match write.write_all(data_to_send_with_header.as_slice()).await {
        Ok(_) => println!("数据已成功发送"),
        Err(e) => {
            panic!("发送数据失败: {:?}", e);
        }
    }
    tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
}
